package com.maimang.platform.controller.system;

import com.maimang.platform.annotation.Log;
import com.maimang.platform.base.BaseController;
import com.maimang.platform.base.Result;
import com.maimang.platform.common.entity.SysUser;
import com.maimang.platform.common.service.*;
import com.maimang.platform.enums.BusinessType;
import com.maimang.platform.enums.Status;
import com.maimang.platform.lang.StringUtils;
import com.maimang.platform.page.TableDataInfo;
import com.maimang.platform.shiro.service.SysPasswordService;
import com.maimang.platform.common.utils.ExcelUtil;
import com.maimang.platform.common.utils.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author Rocky
 * @version 1.0.0
 * @类名 SysUserController
 * @描述 <br>用户信息业务处理</br>
 * @日期 2019-03-28
 * @email jintaozhao@qq.com
 */
@Controller
@RequestMapping("/system/user")
@Api(value = "用户信息", description = "用户信息业务操作处理")
public class SysUserController extends BaseController {
	private String prefix = "system/user";

	@Autowired
	private SysUserService userService;

	@Autowired
	private SysRoleService roleService;

	@Autowired
	private SysConfigService configService;

	@Autowired
	private SysPostService postService;

	@Autowired
	private SysPasswordService passwordService;

	@Autowired
	private SysDeptService deptService;

	@RequiresPermissions("system:user:view")
	@GetMapping()
	public String user() {
		return prefix + "/user";
	}

	@ApiOperation(value = "用户列表", notes = "系统用户信息列表")
	@RequiresPermissions("system:user:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(SysUser user) {
		startPage();
		List<SysUser> list = userService.selectUserList(user);
		return getDataTable(list);
	}

	@Log(title = "用户管理", businessType = BusinessType.EXPORT)
	@RequiresPermissions("system:user:export")
	@PostMapping("/export")
	@ResponseBody
	public Result export(SysUser user) {
		List<SysUser> list = userService.selectUserList(user);
		ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
		return util.exportExcel(list, "用户数据");
	}

	@ApiOperation(value = "导入用户", notes = "通过Excel文件导入用户数据")
	@Log(title = "用户管理", businessType = BusinessType.IMPORT)
	@RequiresPermissions("system:user:import")
	@PostMapping("/importData")
	@ResponseBody
	public Result importData(MultipartFile file, boolean updateSupport) throws Exception {
		ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
		List<SysUser> userList = util.importExcel(file.getInputStream());
		String operName = getSysUser().getLoginName();
		String password = configService.selectConfigByKey("sys.user.initPassword");
		String message = userService.importUser(userList, updateSupport, operName, password);
		return Result.SUCCESS(Status.success.code, message);
	}

	@ApiOperation(value = "导入模板", notes = "导入用户信息Excel模板文件")
	@RequiresPermissions("system:user:view")
	@GetMapping("/importTemplate")
	@ResponseBody
	public Result importTemplate() {
		ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
		return util.importTemplateExcel("用户数据");
	}

	/**
	 * 新增用户
	 */
	@GetMapping("/add")
	public String add(ModelMap modelMap) {
		modelMap.put("roles", roleService.selectRoleAll());
		modelMap.put("posts", postService.selectPostAll());
		return prefix + "/add";
	}

	/**
	 * 新增保存用户
	 */
	@RequiresPermissions("system:user:add")
	@Log(title = "用户管理", businessType = BusinessType.INSERT)
	@ApiOperation(value = "添加用户", notes = "向系统中添加用户数据并初始化密码")
	@PostMapping("/add")
	@Transactional(rollbackFor = Exception.class)
	@ResponseBody
	public Result addSave(SysUser user) {
		if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
			return error("不允许修改超级管理员用户");
		}
		user.setSalt(ShiroUtils.randomSalt());
		user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
		user.setCreateUser(ShiroUtils.getLoginName());
		user.setUpdateUser(ShiroUtils.getLoginName());
		return toResult(userService.insertUser(user));
	}

	/**
	 * 修改用户
	 */
	@GetMapping("/edit/{userId}")
	public String edit(@PathVariable("userId") Long userId, ModelMap modelMap) {
		modelMap.put("user", userService.selectUserById(userId));
		modelMap.put("roles", roleService.selectRolesByUserId(userId));
		modelMap.put("posts", postService.selectPostsByUserId(userId));
		modelMap.put("depts", deptService.selectDeptsByUserId(userId));

		return prefix + "/edit";
	}

	/**
	 * 修改保存用户
	 */
	@RequiresPermissions("system:user:edit")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@ApiOperation(value = "修改用户", notes = "修改用户信息")
	@PostMapping("/edit")
	@Transactional(rollbackFor = Exception.class)
	@ResponseBody
	public Result editSave(SysUser user) {
		if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
			return error("不允许修改超级管理员用户");
		}
		user.setUpdateUser(ShiroUtils.getLoginName());
		return toResult(userService.updateUser(user));
	}

	@RequiresPermissions("system:user:resetPwd")
	@Log(title = "重置密码", businessType = BusinessType.UPDATE)
	@GetMapping("/resetPwd/{userId}")
	public String resetPwd(@PathVariable("userId") Long userId, ModelMap modelMap) {
		modelMap.put("user", userService.selectUserById(userId));
		return prefix + "/resetPwd";
	}

	@RequiresPermissions("system:user:resetPwd")
	@Log(title = "重置密码", businessType = BusinessType.UPDATE)
	@ApiOperation(value = "重置密码", notes = "重置用户密码")
	@PostMapping("/resetPwd")
	@ResponseBody
	public Result resetPwdSave(SysUser user) {
		user.setSalt(ShiroUtils.randomSalt());
		user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
		return toResult(userService.resetUserPwd(user));
	}

	@RequiresPermissions("system:user:remove")
	@Log(title = "用户管理", businessType = BusinessType.DELETE)
	@ApiOperation(value = "删除用户", notes = "用户管理-根据用户id删除用户")
	@PostMapping("/remove")
	@ResponseBody
	public Result remove(String ids) {
		try {
			return toResult(userService.deleteUserByIds(ids));
		} catch (Exception e) {
			return error(e.getMessage());
		}
	}

	/**
	 * 校验用户名
	 */
	@PostMapping("/checkLoginNameUnique")
	@ApiOperation(value = "校验用户名", notes = "校验用户名唯一性")
	@ResponseBody
	public String checkLoginNameUnique(SysUser user) {
		return userService.checkLoginNameUnique(user.getLoginName());
	}

	/**
	 * 校验手机号码
	 */
	@PostMapping("/checkPhoneUnique")
	@ApiOperation(value = "校验手机号", notes = "校验用户绑定的手机号码是否存在")
	@ResponseBody
	public String checkPhoneUnique(SysUser user) {
		return userService.checkPhoneUnique(user);
	}

	/**
	 * 校验email邮箱
	 */
	@PostMapping("/checkEmailUnique")
	@ApiOperation(value = "校验邮箱", notes = "校验用户绑定的邮箱是否已用")
	@ResponseBody
	public String checkEmailUnique(SysUser user) {
		return userService.checkEmailUnique(user);
	}

	/**
	 * 加载用户菜单列表树
	 */
	@ApiOperation(value = "用户菜单列表", notes = "根据部门id加载用户菜单列表树")
	@GetMapping("/selectUserByDeptId/{deptId}")
	@ResponseBody
	public List<SysUser> selectUserByDeptId(@PathVariable("deptId") Long deptId) {
		SysUser user = new SysUser();
		user.setDeptId(deptId);
		List<SysUser> list = userService.selectUserList(user);
		return list;
	}

	/**
	 * 选择部门树
	 */
	@GetMapping("/selectDeptTree/{deptId}")
	public String selectDeptTree(@PathVariable("deptId") Long deptId, ModelMap modelMap) {
		SysUser user = new SysUser();
		user.setDeptId(deptId);
		List<SysUser> list = userService.selectUserList(user);
		modelMap.put("dept", deptService.selectDeptById(deptId));
		modelMap.put("users", list);
		return prefix + "/tree";
	}

	/**
	 * 跳转到userTree页面，进行人员选择
	 *
	 * @return
	 */
	@RequiresPermissions("system:user:view")
	@GetMapping("/userTree")
	public String userTree() {
		return prefix + "/userTree";
	}

	/**
	 * 用户状态修改
	 */
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@ApiOperation(value = "修改用户状态", notes = "修改用户状态，可用或不可用")
	@RequiresPermissions("system:user:edit")
	@PostMapping("/changeStatus")
	@ResponseBody
	public Result changeStatus(SysUser user) {
		return toResult(userService.changeStatus(user));
	}
}